package com.xuanzheng.company.servlet;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.xuanzheng.company.entity.AttendanceSetting;
import com.xuanzheng.company.entity.EmployeePerformance;
import com.xuanzheng.company.entity.User;
import com.xuanzheng.company.service.AttendanceSettingService;
import com.xuanzheng.company.service.EmployeePerformanceService;
import com.xuanzheng.company.service.impl.AttendanceSettingServiceImpl;
import com.xuanzheng.company.service.impl.EmployeePerformanceServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.time.LocalDate;
import java.time.YearMonth;
import java.util.List;

@WebServlet("/api/employee/performance")
public class EmployeePerformanceServlet extends HttpServlet {
    private EmployeePerformanceService employeePerformanceService = new EmployeePerformanceServiceImpl();
    private AttendanceSettingService attendanceSettingService = new AttendanceSettingServiceImpl();
    private Gson gson = new Gson();
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        JsonObject result = new JsonObject();
        
        // 获取当前登录用户
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("user");
        
        if (user == null) {
            result.addProperty("success", false);
            result.addProperty("message", "用户未登录");
            out.print(gson.toJson(result));
            return;
        }
        
        // 检查用户是否是公司负责人
        if (user.getRole() != 1) {
            result.addProperty("success", false);
            result.addProperty("message", "只有公司负责人可以查看员工绩点");
            out.print(gson.toJson(result));
            return;
        }
        
        String companyId = user.getCompanyId();
        if (companyId == null || companyId.isEmpty()) {
            result.addProperty("success", false);
            result.addProperty("message", "未找到公司信息");
            out.print(gson.toJson(result));
            return;
        }
        
        // 获取请求参数中的年份和月份
        String yearParam = req.getParameter("year");
        String monthParam = req.getParameter("month");
        
        int year;
        int month;
        
        // 如果没有指定年份和月份，则使用当前年月
        if (yearParam == null || monthParam == null) {
            LocalDate now = LocalDate.now();
            year = now.getYear();
            month = now.getMonthValue();
        } else {
            try {
                year = Integer.parseInt(yearParam);
                month = Integer.parseInt(monthParam);
                
                // 验证年月的有效性
                if (year < 2000 || year > 2100 || month < 1 || month > 12) {
                    result.addProperty("success", false);
                    result.addProperty("message", "无效的年份或月份");
                    out.print(gson.toJson(result));
                    return;
                }
            } catch (NumberFormatException e) {
                result.addProperty("success", false);
                result.addProperty("message", "无效的年份或月份格式");
                out.print(gson.toJson(result));
                return;
            }
        }
        
        try {
            // 获取绩点设置
            AttendanceSetting setting = attendanceSettingService.getByCompanyId(companyId);
            if (setting == null) {
                result.addProperty("success", false);
                result.addProperty("message", "请先设置打卡和绩点参数");
                out.print(gson.toJson(result));
                return;
            }
            
            // 获取员工绩点记录
            List<EmployeePerformance> performances = employeePerformanceService.getPerformancesByCompanyIdAndYearMonth(
                    companyId, year, month);
            
            result.addProperty("success", true);
            result.add("performances", gson.toJsonTree(performances));
            result.addProperty("month", month);
            result.addProperty("year", year);
            
            // 添加绩点设置信息
            JsonObject settingInfo = new JsonObject();
            settingInfo.addProperty("maxAttendanceHours", setting.getMaxAttendanceHours());
            settingInfo.addProperty("attendancePercentage", setting.getAttendancePercentage());
            settingInfo.addProperty("taskPercentage", setting.getTaskPercentage());
            result.add("settings", settingInfo);
            
            // 添加是否有存档记录的标志
            result.addProperty("hasRecord", !performances.isEmpty());
            
        } catch (Exception e) {
            e.printStackTrace();
            result.addProperty("success", false);
            result.addProperty("message", "获取员工绩点数据失败: " + e.getMessage());
        }
        
        out.print(gson.toJson(result));
    }
    
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        JsonObject result = new JsonObject();
        
        // 获取当前登录用户
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("user");
        
        if (user == null) {
            result.addProperty("success", false);
            result.addProperty("message", "用户未登录");
            out.print(gson.toJson(result));
            return;
        }
        
        // 检查用户是否是公司负责人
        if (user.getRole() != 1) {
            result.addProperty("success", false);
            result.addProperty("message", "只有公司负责人可以上传员工绩点");
            out.print(gson.toJson(result));
            return;
        }
        
        String companyId = user.getCompanyId();
        if (companyId == null || companyId.isEmpty()) {
            result.addProperty("success", false);
            result.addProperty("message", "未找到公司信息");
            out.print(gson.toJson(result));
            return;
        }
        
        // 读取请求体中的JSON数据
        BufferedReader reader = req.getReader();
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        
        try {
            // 解析JSON数据
            JsonObject jsonObject = gson.fromJson(sb.toString(), JsonObject.class);
            
            int year = jsonObject.has("year") ? jsonObject.get("year").getAsInt() : LocalDate.now().getYear();
            int month = jsonObject.has("month") ? jsonObject.get("month").getAsInt() : LocalDate.now().getMonthValue();
            
            // 验证年月的有效性
            if (year < 2000 || year > 2100 || month < 1 || month > 12) {
                result.addProperty("success", false);
                result.addProperty("message", "无效的年份或月份");
                out.print(gson.toJson(result));
                return;
            }
            
            // 上传员工绩点记录
            boolean success = employeePerformanceService.uploadCurrentMonthPerformances(companyId, year, month);
            
            if (success) {
                result.addProperty("success", true);
                result.addProperty("message", "员工绩点上传成功");
            } else {
                result.addProperty("success", false);
                result.addProperty("message", "员工绩点上传失败");
            }
            
        } catch (Exception e) {
            e.printStackTrace();
            result.addProperty("success", false);
            result.addProperty("message", "请求数据格式错误: " + e.getMessage());
        }
        
        out.print(gson.toJson(result));
    }
} 